package com.example.game.service.Impl;

import com.example.game.service.IGameService;

import com.pojo.Entity.Game;
import com.pojo.dto.ToGame;
import com.pojo.mapper.GameMapper;
import com.pojo.util.Tool;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class GameServiceImpl implements IGameService {

    @Autowired
    GameMapper gameMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    private static final String GAME_KEY="GAME_KEY_GET:";
    private static final String GAME_LOCK_KEY="GAME_LOCK_KEY:";
    @Override
    public Integer insert(Game game, HttpServletRequest httpServletRequest) {
        String identifying=httpServletRequest.getHeader("identifying");
        Integer uID= (Integer) redisTemplate.opsForHash().get(identifying,"uID");
        game.setGRecoders(uID);
        Integer count=gameMapper.insert(game);
        return  count;
    }
    @Override
    public Integer update(Game game, HttpServletRequest httpServletRequest) {
        String identifying=httpServletRequest.getHeader("identifying");
        Integer uID= (Integer) redisTemplate.opsForHash().get(identifying,"uID");
        game.setGRecoders(uID);
        String nky=GAME_KEY+String.valueOf(game.getGID());
        String lnky=GAME_LOCK_KEY+String.valueOf(game.getGID());
        try {
            return Tool.updateToRedis(site1->gameMapper.update(site1),game,nky,lnky,redisTemplate,redissonClient);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<ToGame> getlGame(Integer Page, Integer Number) {
        Page=(Page-1)*Number;
        return gameMapper.getlGame(Page,Number);
    }
    @Override
    public Game getGame(Integer gID) {
        String sky=GAME_KEY+String.valueOf(gID);
        String lsky=GAME_LOCK_KEY+String.valueOf(gID);
        Game game= (Game) redisTemplate.opsForValue().get(sky);
        if(game==null) {
            try {
                game = (Game) Tool.putDateToRedis(sID1 -> gameMapper.findBygID(gID), gID, sky,lsky,new Game(),redisTemplate,redissonClient);
                return game;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return game;
    }
}
